package com.loong.controller;

import com.loong.dto.LoginDTO;
import com.loong.entity.Emp;
import com.loong.entity.LoginInfo;
import com.loong.result.Result;
import com.loong.service.EmpService;
import com.loong.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result<LoginInfo> login(@Validated @RequestBody LoginDTO loginDTO) {
        Emp loginEmp = empService.login(loginDTO);
        if (loginEmp != null) {
            Map<String , Object> claims = new HashMap<>();
            claims.put("id", loginEmp.getId());
            claims.put("username",loginEmp.getUsername());
            claims.put("name",loginEmp.getName());
            String token = JwtUtils.generateJwt(claims);
            return Result.success(new LoginInfo(loginEmp.getId(), loginEmp.getUsername(), loginEmp.getName(), token));
        }
        return Result.error("用户名或密码错误");
    }
}
